package com.qianfeng.Event.listener;

import com.qianfeng.Event.DeviceCommandEvent;
import com.qianfeng.pojo.SysHumiture;
import com.sun.org.apache.bcel.internal.generic.IFNE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

/*
 *@Description:
 *@author:刘哥
 *@Date:86180 2022/9/14 20:43
 */
@Component
public class SysHumitureListener {

    private ApplicationContext context;
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    /*
        CopyOnWriteArrayList相当于线程安全的Arraylist集合,
        适合用在:：List 大小通常保持很小，只读操作远多于可变操作，需要在遍历期间防止线程间的冲突。
        查询快,可以多次进行查询，减少修改,迭代器遍历特别快
         */
    public final List<SysHumiture> humitureList = new CopyOnWriteArrayList<>();

    @EventListener
    @Async
    public void onHumiture(SysHumiture humiture) {
        humitureList.add(humiture);
    }

    //    配置一个定时器,多久进行一次温湿度的计算
//    @Scheduled(cron = "* 0/1 * * * * ?")
    @Scheduled(fixedRate = 60000)//每60秒执行一次，不收任何其他的事务影响
    public void checkHumiture() {
        if(humitureList.size()==0){
            return;
        }
        ArrayList<SysHumiture> subList = new ArrayList<>();
        subList.addAll(humitureList);
//        清楚之前存入的数据
        humitureList.clear();
//        计算温度平均值
        double tempAvg = subList.stream().mapToDouble(SysHumiture::getTemperature).average().getAsDouble();
        if (tempAvg > 0) {
            String deviceId = subList.stream().filter(humiture -> humiture.getDeviceId() !=null).toString();
            if(tempAvg>35){
                System.out.println("当前温度大于设定的阈值,打开空调 " + tempAvg);
                context.publishEvent(new DeviceCommandEvent(deviceId,"0"));
            }else if (tempAvg<32){
                System.err.println("当前温度小于设定的阈值,关闭空调");
                //写死了一个操作
                context.publishEvent(new DeviceCommandEvent(deviceId,"1"));
            }
        }
    }
}

